import { Context, Next} from 'koa'
import service from '../service/user.service'
import {IUser, baseMiddlewareFunction} from '../types/user.types'
import md5password from '../utils/password-handle'
import {
  USERNAME_OR_PASSWORD_IS_REQUIRED,
  USERNAME_ALREADY_EXISTS
} from '../constants/error-types'

const verifyUser = async (ctx: Context, next: Next): Promise<string|unknown> => {
  // 获取用户名密码
  const {username, password} = ctx.request.body as unknown as IUser
  // 判断用户名或者密码为空
  if (!username || !password) {
    const error: Error = new Error(USERNAME_OR_PASSWORD_IS_REQUIRED)
    return ctx.app.emit('error', ctx, error)
  }

  // 判断用户名是否注册过
  const result: any = await service.getUserByName(username)
  if (result[0].length) {
    const error: Error = new Error(USERNAME_ALREADY_EXISTS)
    return ctx.app.emit('error', ctx, error)
  }
  await next()
}

const handlePassword: baseMiddlewareFunction<void> = async (ctx: Context, next: Next) =>  {
  const { password } = ctx.request.body as unknown as IUser

  // @ts-ignore
  ctx.request.body.password = md5password(password)
  await next()
}
export {
  verifyUser,
  handlePassword
}